<template>
  <div class="CRContainer">
    <div class="commonTitle">
      <div class="commonTitleMain">
        <h2>
          <Icon class="back" type="md-arrow-back" @click="$router.back(-1)"/>
          课次记录 <span @click="isStyleDebug = !isStyleDebug">每月最多调整5次课次</span></h2>
      </div>
    </div>

    <div class="crHeader2">
      <div class="crHeader2-main">
        <!--<p></p>-->
        <div class="crHeader2-right">
          <p class="crHeader2-tab">
          <span v-for="(item,$index) in classType" :class="{active:i==$index}"
                @click="selectClassType(item.value,$index)">{{item.name}}</span>
          </p>
        </div>
      </div>
    </div>
    <div class="crBody">
      <div class="tableContent">
        <Table
          class="tableData"
          @on-selection-change="selectChange"
          :columns="formalHeadersNew"
          :data="formalList"
        >
          <!--<template slot-scope="{ row, index }" slot="sys_calc_hour">-->
            <!--<p v-if="row.sys_calc_hour==''">&#45;&#45;</p>-->
            <!--&lt;!&ndash;<p v-else-if="row.sys_calc_hour=='确认课时'"  class="btn disabled">确认课时</p>&ndash;&gt;-->
            <!--<p v-else-if="row.sys_calc_hour=='确认课时'" class="btn" @click="confirmHour(row)">确认课时</p>-->
            <!--<p v-else>{{row.sys_calc_hour}}</p>-->
          <!--</template>-->
          <!--<template slot-scope="{ row, index }" slot="entry_records">-->
            <!--<p v-if="row.entry_records==''">&#45;&#45;</p>-->
            <!--<p v-else class="btn4" @click="viewRcord(row.id)">查看记录</p>-->
          <!--</template>-->
          <template slot-scope="{ row, index }" slot="teacherOperate">
            <div  v-if="row.total_common_length>0">
              <div class="teacherOperate"  v-if="row.confirm_length==''||row.confirm_length==null">
                <p class="btn3" @click="confirmHour(row)">确认时长</p>
                <p class="btn3 btn5" @click="viewRcord(row.id)">查看明细</p>
              </div>
              <div class="teacherOperate" v-else>
                <p class="btn3 disabled">已确认</p>
                <p class="btn3 btn5" @click="viewRcord(row.id)">查看明细</p>
              </div>
            </div>
            <div class="teacherOperate" v-else>
            </div>
          </template>

          <template slot-scope="{ row, index }" slot="teacherOperate">
            <div class="teacherOperate"  v-if="row.confirm_btn_status==0"><!--还未上课-->
              <p style="width:66px;text-align: center">--</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==1">
              <p class="btn3 btn6" @click="complain(row)">报备申请</p>
              <p class="btn3" @click="confirmHour(row)">确认课时</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==2"><!--系统核算中-->
              <p style="width:66px;text-align: center">--</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==3"><!--已确认课时-->
              <p style="width:66px;text-align: center">--</p>
              <p class="btn3 disabled">已确认</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==4"><!--未上课-->
              <p class="btn3 btn6" @click="complain(row)">报备申请</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==5"><!--已报备-->
              <p class="btn3 disabled">报备中</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==6"><!--报备被拒绝-->
              <p class="btn3 btn6" @click="complain(row)">再次报备</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
            <div class="teacherOperate"  v-else-if="row.confirm_btn_status==7"><!--报备成功-->
              <p class="btn3 disabled">报备成功</p>
              <p style="width:66px;text-align: center">--</p>
            </div>
          </template>

          <!--查看明细-->
          <template slot-scope="{ row, index }" slot="viewRcord">
            <p v-if="row.confirm_btn_status==3" class="btn3 btn5" @click="viewRcord(row.id)">查看明细</p>
            <p v-else>--</p>
          </template>
          <!--调整课次-->
          <template slot-scope="{ row, index }" slot="changeClass">
            <p v-if="row.can_adjust==0">--</p>
            <p v-else-if="row.can_adjust==1" class="btn" @click="changeClass(row)">调整课次</p>
          </template>

        </Table>
        <Page
          :total="formalTotal"
          show-sizer
          show-elevator
          @on-change="followUpPageChange"
          @on-page-size-change="followUpPageSizeChange"
          show-total
        />
      </div>
    </div>
    <!--确认课时-->
    <Modal v-model="confirmHourModal" width="550" class="confirmHour" :mask-closable="false">
      <p slot="header">
        <span>确认课时</span>
      </p>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>
      <Form ref="formItem" :model="formItem" :rules="ruleItem" :label-width="90">
        <FormItem label="姓名:">
          {{classInfo.name}}
        </FormItem>
        <FormItem label="上课时间:">
          {{classInfo.planned_date}} {{classInfo.planned_start_time}}-{{classInfo.planned_end_time}}
        </FormItem>
        <FormItem label="计划课时:">
          {{classInfo.class_hour_consumption}}课时
        </FormItem>
        <FormItem label="系统时长:">
          {{classInfo.total_common_length||0}}min
        </FormItem>
        <FormItem label="教学核算:">
          {{classInfo.sys_calc_hour||0}}min
        </FormItem>
        <!--<FormItem class="block" label="是否有异议:" prop="is_objection">-->
        <!--<RadioGroup v-model="formItem.is_objection" @on-change="is_objection">-->
        <!--<Radio :label="0">无</Radio>-->
        <!--<Radio :label="1">有</Radio>-->
        <!--</RadioGroup>-->
        <!--</FormItem>-->

        <FormItem class="block" v-if="formItem.is_objection==0" prop="standard_class_feedback" label="课程反馈:">
          <Input type="textarea" v-model="formItem.standard_class_feedback" placeholder="请输入课程反馈..." style="width:350px"
                 :autosize="{minRows: 4,maxRows: 16}"></Input>
        </FormItem>
        <FormItem class="block" v-if="formItem.is_objection==1" prop="objection_feedback" label="异议反馈:">
          <Input type="textarea" v-model="formItem.objection_feedback" placeholder="请输入异议反馈..." style="width:350px"
                 :autosize="{minRows: 10,maxRows: 16}"></Input>
        </FormItem>
      </Form>
      <Button class="submit" type="primary" @click="confirm('formItem')">确认</Button>
      <p slot="footer"></p>
    </Modal>
    <!--查看记录-->
    <Modal v-model="viewRcordModal" width="860" class="viewRcord" :mask-closable="false">
      <p slot="header">
        <span>查看记录</span>
      </p>
      <div class="tableContent tableContent2">
        <Table
          class="tableData"
          :columns="recordHeaders"
          :data="recordList"
          border
        >
          <template slot-scope="{ row, index }" slot="room_type">
            <p v-if="row.room_type==2">嗨课堂</p>
            <p v-else-if="row.room_type==1">好视通</p>
          </template>
        </Table>
      </div>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>

      <p slot="footer"></p>
    </Modal>
    <!--调整课次-->
    <Modal v-model="changeClassModal" width="380" class="changeClass" :mask-closable="false">
      <p slot="header">
        <span>调整课次</span>
      </p>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>
      <Form :model="formValidate" :label-width="70">
        <FormItem label="选择日期:">
          <DatePicker type="date"
                      :options="options"
                      transfer
                      placeholder="请选择"
                      v-model="formValidate.class_planned_date"
                      :clearable="false"
                      @on-change="isClick"></DatePicker>
        </FormItem>
        <FormItem label="开始时间:">
          <Cascader :data="startTimeData"
                    v-model="startTimeValue"
                    :clearable="false"
                    transfer
                    :render-format="label => label.join(' : ')"
                    @on-change="isClick"
                    style="width: 196px;"></Cascader>
        </FormItem>
        <FormItem label="上课时长:">
          {{formValidate.duration}}min
        </FormItem>
        <Button class="submit" type="primary" :class="{ active: isLoad }" :loading="loadingPaike"
                @click="handleSubmit">调整课次
        </Button>
      </Form>
      <p slot="footer"></p>
    </Modal>
    <!--报备申请-->
    <Modal v-model="complainModal" width="550" class="confirmHour" :mask-closable="false">
      <p slot="header">
        <span>报备申请</span>
      </p>
      <p slot="close">
        <img src="../../assets/images/close2.png" alt="关闭">
      </p>
      <Form ref="complainFormItem" :model="complainFormItem" :rules="complainRuleItem" :label-width="90">
        <FormItem label="学生姓名:">
          {{classInfo.name}}
        </FormItem>
        <FormItem label="上课时间:">
          {{classInfo.planned_date}} {{classInfo.planned_start_time}}-{{classInfo.planned_end_time}}
        </FormItem>
        <FormItem label="系统时长:">
          {{classInfo.total_common_length||0}}min
        </FormItem>
        <FormItem label="教学核算:">
          {{classInfo.sys_calc_hour||0}}min
        </FormItem>
        <FormItem class="block" prop="appeal_content" label="报备内容:">
          <Input type="textarea" v-model="complainFormItem.appeal_content" placeholder="请输入报备内容..." style="width:350px"
                 :autosize="{minRows: 10,maxRows: 16}"></Input>
        </FormItem>
      </Form>
      <Button class="submit" type="primary" @click="complain2('complainFormItem')">确认</Button>
      <p slot="footer"></p>
    </Modal>
  </div>
</template>
<style lang="less">
  @import '../../style/classRecord.less';

  .commonTitleMain {
    .back {
      color: #000;
      font-size: 22px;
      vertical-align: -4px;
    }
  }
</style>
<script>
  import {timestamp} from '@/common/js/common';
  import {GetQueryString} from '../../common/js/common';
  import {apiBase3} from '@/common/js/api.config';

  export default {

    watch: {
      formalHeaders(value) {
        this.formalHeadersNew = value.map(i => {
          const setWidthStyle = localStorage.widthStyle ? JSON.parse(localStorage.widthStyle) : {}
          const fixWidthStyle = {
            class_status: 92,
            class_type: 92,
            grade: 73,
            name: 80,
            planned_date: 120,
            total_common_length: 92,
            planned_end_time: 120,
            planned_start_time: 120,
            ...setWidthStyle,
          }
          return {
            ...i,
            width: fixWidthStyle[i.key] || i.width,
            renderHeader: (h, params) => {
              return (
                <div>
                {params.column.title}
            <div style={this.isStyleDebug && "display: none"}>
            <div
              onClick={() => {
                params.column.width = +params.column.width + 1;
                const localStyle = localStorage.widthStyle ? JSON.parse(localStorage.widthStyle) : {}
                const widthStyle = {...localStyle}
                widthStyle[params.column.key] = +params.column.width
                localStorage.widthStyle = JSON.stringify(widthStyle)
              }}
            >
              +
              </div>
              {params.column.width} px
              <div
              onClick={() => {
                params.column.width = +params.column.width - 1;
                const localStyle = localStorage.widthStyle ? JSON.parse(localStorage.widthStyle) : {}
                const widthStyle = {...localStyle}
                widthStyle[params.column.key] = +params.column.width
                localStorage.widthStyle = JSON.stringify(widthStyle)
              }}
            >
              -
              </div>
              </div>
              </div>
            );
            }
          };
        });
      },
    },
    data() {
      return {
        formalHeadersNew: [],
        isStyleDebug: true,
        getClassEachListBySchedules: this.$store.state.getClassEachListBySchedules,//根据课程计划获取课次记录
        confirmClassActualHour: this.$store.state.confirmClassActualHour,//根据课程计划获取课次记录
        getRoomRecords: this.$store.state.getRoomRecords,//获取进出房间记录
        adjustFormalClass: this.$store.state.adjustFormalClass,//调整课次
        classType: [//课程类型
          {
            name: "全部",
            value: [1, 2, 3, 4, 5]
          },
          {
            name: "待上课",
            value: [1]
          },
          {
            name: "已上课",
            value: [2]
          },
          {
            name: "未上课",
            value: [3, 4]
          },
          {
            name: "已结算",
            value: [5]
          },
        ],
        i: 0, //类型选中下标
        formData: {  //请求数据
          class_schedule_id: "",
          class_status: [1, 2, 3, 4, 5],
          page: 1,
          size: 10,
        },
        formalHeaders: [],
        formalList: [],
        formalTotal: 0,
        //调整课次弹窗
        changeClassModal: false,
        options: {
          disabledDate(date) {
            return date && date.valueOf() < Date.now() - 86400000;
          }
        },
        formValidate: {
          id: "",
          class_planned_date: "",
          class_planned_start_time: "",
          class_planned_end_time: "",
          duration: "",
        },
        loadingPaike: false,
        startTimeValue: [],  //开始时间列表
        startTimeData: [],  //开始时间选中
        arrangeCourse: this.$store.state.arrangeCourse,
        isLoad: false,  //loading
        //确认课时弹窗
        confirmHourModal: false,
        classInfo: {},
        formItem: {
          class_each_id: "",
          is_objection: 0,
          standard_class_feedback: "",
          objection_feedback: "",
        },
        ruleItem: {
          is_objection: [{type: "number", required: true, message: '请选择是否有异议', trigger: 'blur'}],
          standard_class_feedback: [{required: true, message: '请输入课程反馈', trigger: 'blur'}],
          objection_feedback: [{required: true, message: '请输入异议反馈', trigger: 'blur'}],
        },
        //查看记录弹窗
        viewRcordModal: false,
        recordHeaders: [
          {
            title: "姓名",
            key: "real_name",
            width: 130,
          },
          {
            title: "客户端类型",
            key: "room_type",
            width: 130,
            slot:"room_type"
          },
          {
            title: "用户类型",
            key: "user_type",
            width: 120,
          },
          {
            title: "进入时间",
            key: "enter_time",
            width: 180,
          },
          {
            title: "退出时间",
            key: "leave_time",
            width: 180,
          },
        ],
        recordList: [],
        //申请报备弹窗
        complainAPI: this.$store.state.appeal,//确认课时api
        complainModal: false,
        complainFormItem: {
          class_each_id: "",
          appeal_content: "",
        },
        complainRuleItem: {
          appeal_content: [{required: true, message: '请输入报备内容', trigger: 'blur'}],
        },
      }
    },
    mounted() {
      this.classRecordList();
      this.formData.class_schedule_id = this.$route.query.id;
    },
    updated() {
    },
    methods: {
      selectClassType(value, index) {  //课程类型选择
        this.i = index;
        this.formData.class_status = value;
        this.classRecordList();
      },
      classRecordList() {  //查询课次记录列表
        this.$axios.post(this.$store.state.getClassEachListBySchedules, this.formData, {
          baseURL: apiBase3(),
        }).then(({data}) => {
          // this.formalHeaders = [
          //   {
          //     type: "selection",
          //     width: 60,
          //     align: "center"
          //   },
          // ];
          this.formalHeaders = [];
          let columns = data.data.columns;
          for (var key in columns) {
            // if (key == "sys_calc_hour" || key == "entry_records") {
            //   this.formalHeaders.push(
            //     {
            //       title: columns[key],
            //       slot: key,
            //       key,
            //       width: 120
            //     }
            //   )
            // }
            // else
            if (key === "planned_start_time" || key == "planned_end_time") {
              this.formalHeaders.push(
                {
                  title: '排课' + columns[key],
                  key,
                  width: 120
                }
              )
            }
            else {
              this.formalHeaders.push(
                {
                  title: columns[key],
                  key: key,
                  width: 120
                }
              )
            }
          }
          this.formalHeaders.push({
            title: "老师操作",
            key: 'teacherOperate',
            slot: "teacherOperate",
            width: 190
          }, {
            title: "查看明细",
            key: 'viewRcord',
            slot: "viewRcord",
            width: 120
          },{
            title: "调整课次",
            key: 'change_class',
            slot: "changeClass",
            width: 120
          })

          // console.log(this.formalHeaders);
          this.formalList = data.data.data;
          this.formalTotal = data.data.pagination.total;
        })
      },
      followUpPageChange(page) {
        //页码改变
        this.formData.page = page;
        this.classRecordList();
      },
      followUpPageSizeChange(pageSize) {
        //页码size改变
        this.formData.size = pageSize;
        this.classRecordList();
      },
      selectChange() {

      },
      //调整课次
      changeClass(item) {
        console.log(item);
        this.formValidate.id = item.id;
        this.formValidate.class_planned_date = item.planned_date;
        this.formValidate.class_planned_start_time = item.planned_start_time;
        this.startTimeValue = item.planned_start_time.split(":");
        this.formValidate.duration = item.duration;

        this.changeClassModal = true;
        let minutes = []
        for (let i = 0; i < 12; i++) {   //开始时间分钟 间隔五分钟
          let num = i * 5 < 10 ? `0${i * 5}` : `${i * 5}`
          minutes.push({
            value: num,
            label: num,
          })
        }

        for (let i = 6; i < 24; i++) { //开始时间小时 6-24
          let num = i < 10 ? `0${i}` : `${i}`
          this.startTimeData.push({
            value: num,
            label: num,
            children: minutes,
          })
        }
      },
      isClick(value) {  // 表单验证正确，排课按钮变蓝
        console.log(value);
        if (Array.isArray(value)) {
          Object.assign(this.formValidate, {
            class_planned_start_time: value.join(':')
          })
        }

      },
      // 点击调整课次
      handleSubmit() {
        this.loadingPaike = true;
        let date = this.formValidate.class_planned_date;
        let formatDate = this.moment(date).format('YYYY-MM-DD');
        let times = this.formValidate.class_planned_start_time;
        let dateTime = formatDate + " " + times;
        let chooseTime = this.moment(dateTime).format('x');
        let endDate = this.moment(dateTime).add(Number(this.formValidate.duration), 'm');
        let endHour = endDate.hour() < 10 ? `0${endDate.hour()}` : `${endDate.hour()}`;
        let endMinute = endDate.minute() < 10 ? `0${endDate.minute()}` : `${endDate.minute()}`;
        this.formValidate.class_planned_date = formatDate;
        // this.formValidate.class_planned_end_time = endHour + ":" + endMinute;
        // console.log(this.formValidate.class_planned_end_time);
        timestamp().then(res => {
          let nowTime = res.timestamp;
          if (chooseTime < nowTime) {
            this.$Notice.error({
              title: '提示',
              desc: '选择时间已经超过当前时间，无法排课！',
              duration: 5,
            });
            this.loadingPaike = false
          } else if ((endHour > 0 && endHour < 6) || (endHour == 0 && endMinute > 0)) {
            this.$Notice.error({
              title: '提示',
              desc: '结束时间不能超过24点！',
              duration: 5,
            });
            this.loadingPaike = false
          } else {
            this.isLoad = true;
            // let formItem = JSON.parse(JSON.stringify(this.formItem));
            // Object.assign(formItem, {
            //   courseDate: formatDate,
            //   courseLength: Number(formItem.courseLength)
            // })
            this.$axios.post(this.adjustFormalClass, this.formValidate, {
              baseURL: apiBase3(),
            }).then(res => {
              this.changeClassModal = false;
              this.$Message.success('调整成功！');
              this.loadingPaike = false;
              this.isLoad = false;
              this.classRecordList();
            }).catch(error => {
              // this.changeClassModal = false;
              this.loadingPaike = false
              this.isLoad = false
            });
          }
        });
      },
      //确认课时
      confirmHour(item) {
        this.classInfo = item;
        this.formItem.class_each_id = item.id
        this.confirmHourModal = true;
        this.formItem.standard_class_feedback = '';//初始化
      },
      is_objection(value) {
        console.log(value);
        if (value == 1) {
          this.formItem.standard_class_feedback = '';
        }
        else {
          this.formItem.objection_feedback = '';
        }
      },
      confirm(name) {//确认课时-点击确定
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$axios.post(this.confirmClassActualHour, this.formItem, {
              baseURL: apiBase3(),
            }).then(res => {
              this.$Notice.success({
                title: '',
                desc: '确认成功',
                duration: 3
              });
              this.confirmHourModal = false;
              this.classRecordList();
            });
          }
        });
      },

      //查看记录
      viewRcord(id) {
        this.viewRcordModal = true;
        this.$axios.post(this.getRoomRecords, {
          class_each_id: id
        }, {
          baseURL: apiBase3(),
        }).then(res => {
          this.recordList = [...res.data.data.hkt, ...res.data.data.hst]
          // this.recordList=res.data.data.hst;
        });
      },
      //报备申请
      complain(item) {
        this.classInfo = item;
        this.complainFormItem.class_each_id = item.id;
        this.complainModal = true;
        this.complainFormItem.appeal_content = "";
      },
      complain2(name) {//报备申请-点击确定
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$axios.post(this.complainAPI, this.complainFormItem, {
              baseURL: apiBase3(),
            }).then(res => {
              this.$Notice.success({
                title: '',
                desc: '报备成功',
                duration: 3
              });
              this.complainModal = false;
              this.classRecordList();
            });
          }
        })
      },
    },
    destroyed() {
    },
  }
</script>
